10. It’s Christmas#

In this lab, we will use functions to help us prepare for Christmas, including decorating a Christmas tree.

1. Christmas BUDGET

  • transportation=10
  • meal = 15
  • presents = 50
  • activities = 25
  • The following code will create a pie chart of this budget.

    import matplotlib.pyplot as plt  #plot library
    fig, ax = plt.subplots(figsize=(5,5)) #you can adjust the figsize  (5,5)=(length,width)
            
    budget_items = ['transportation','meal','presents','activities'] #categories
    budget = [10,15,50,25] #enter the amounts for 'presents' and 'activities
    total=sum(budget)
    ax=plt.pie(budget,labels=budget_items,autopct=lambda p: '${:.0f}'.format(p * total / 100)) #make pie chart  autopct='%1.0f%%'
    plt.gca().set_title("Christmas Budget") #add a title
    
    Text(0.5, 1.0, 'Christmas Budget')
    
    ../../_images/1fad98edd773e61b2b06d0b42c235b2db2e4a3d38fbc6a33d256765fc6fb160c.png

    2. Word Cloud Christmas Card

    We'll use the lyrics to the Twelve Days of Christmas as the background for a Chistmas card.
    import wordcloud
    
    #Define a function which counts the interesting words
    def calculate_frequencies(textfile):
        #list of punctuations
        punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
        #list of uninteresting words 
        uninteresting_words = ["AND","BY","IT","THE","THAT","A","IS","HAD","TO","NOT","BUT","FOR","OF","WHICH","IF","IN","ON","WERE","YE","THOU"]
        
         # removes punctuation and uninteresting words
        import re
        fc1=str(textfile)
        fc2= fc1.split(' ')
        for i in range(len(fc2)): 
            fc2[i] = fc2[i].upper()
        #Remove punctuations
        fc3 = []
        for s in fc2:
            if not any([o in s for o in punctuations]):
                fc3.append(s)
        #Remove uninteresting words
        fc4=[]
        for s in fc3:
            if not any([o in s for o in uninteresting_words]):
                fc4.append(s)
        fc5=[]
        for s in fc4:
            if not any([o.lower() in s for o in uninteresting_words]):
                fc5.append(s)
                
        while('' in fc5) : 
            fc5.remove('') 
            
        import collections
        fc6 = collections.Counter(fc5)
    
        #wordcloud
        cloud = wordcloud.WordCloud( max_words = 12)  #can adjust the number of words
        cloud.generate_from_frequencies(fc6)
        return cloud.to_array()
    
    #Open the text file with the words to be plotted.
    with open('twelvedays.txt','r') as file:  
        carol = file.readlines()
        
    #make the wordcloud   
    carol = calculate_frequencies(carol)
    plt.imshow(carol, interpolation = 'nearest')
    plt.text(-5,70,"Merry Christmas!",color='r',size=40) #Add Christmas! after Merry
    plt.axis('off')
    plt.savefig('card.png', bbox_inches='tight')  
    
    ../../_images/726a8f42672c934f82e409c5d68178f69f74330fff74383fb86090d38a66e930.png

    3. Analysis of Christmas Hits

    Read and display the first five lines in the file christmas_billboard_data.csv. What song appears on the chart the greatest number of times?
    import pandas as pd
    df=pd.read_csv("christmas_billboard_data.csv")
    df.head()
    
    url weekid week_position song performer songid instance previous_week_position peak_position weeks_on_chart year month day
    0 http://www.billboard.com/charts/hot-100/1958-1... 12/13/1958 83 RUN RUDOLPH RUN Chuck Berry Run Rudolph RunChuck Berry 1 NaN 69 3 1958 12 13
    1 http://www.billboard.com/charts/hot-100/1958-1... 12/20/1958 57 JINGLE BELL ROCK Bobby Helms Jingle Bell RockBobby Helms 1 NaN 29 19 1958 12 20
    2 http://www.billboard.com/charts/hot-100/1958-1... 12/20/1958 73 RUN RUDOLPH RUN Chuck Berry Run Rudolph RunChuck Berry 1 83.0 69 3 1958 12 20
    3 http://www.billboard.com/charts/hot-100/1958-1... 12/20/1958 86 WHITE CHRISTMAS Bing Crosby White ChristmasBing Crosby 1 NaN 12 13 1958 12 20
    4 http://www.billboard.com/charts/hot-100/1958-1... 12/27/1958 44 GREEN CHRI$TMA$ Stan Freberg Green Chri$tma$Stan Freberg 1 NaN 44 2 1958 12 27
    df["song"].value_counts()  #add the missing info
    
    song
    JINGLE BELL ROCK                               28
    ALL I WANT FOR CHRISTMAS IS YOU                20
    ROCKIN' AROUND THE CHRISTMAS TREE              19
    WHITE CHRISTMAS                                16
    THE CHIPMUNK SONG (CHRISTMAS DON'T BE LATE)    16
                                                   ..
    BLUE CHRISTMAS                                  1
    CHILD OF GOD                                    1
    GREATEST TIME OF YEAR                           1
    WHERE ARE YOU CHRISTMAS?                        1
    IT'S THE MOST WONDERFUL TIME OF THE YEAR        1
    Name: count, Length: 70, dtype: int64
    

    4. Creating a Christmas Carol

    import numpy as np
    from IPython.display import Audio 
    rest=0
    do=220
    re=9/8*220
    mi=5/4*220
    fa=4/3*220
    so=3/2*220
    la=5/3*220
    ti=15/8*220
    do1=2*220
    re1=2*9/8*220
    mi1=2*5/4*220
    fa1=2*4/3*220
    so1=2*3/2*220
    la1=2*5/3*220
    ti1=2*15/8*220
    do2=2*2*220
    la0=5/3*110
    do0=110
    silentnight=[so,la,so,mi,mi,mi,so,la,so,mi,mi,mi,re1,rest,re1,ti,ti,ti,do1,rest,do1,so,so,so,la,rest,la,do1,ti,la,so,la,so,mi,mi,mi,la,rest,la,do1,ti,la,so,la,so,mi,mi,mi,re1,rest,re1,fa1,re1,ti,do1,do1,do1,mi1,mi1,mi1,do1,so,mi,so,fa,re,do,do,do,do,do,do]
    
    def play(song):
        song=np.array(song)
        framerate = 44100
        t = np.linspace(0, len(song) / 2, round(framerate * len(song) / 2))[:-1]
        song_idx = np.floor(t * 2).astype(int)
        data = np.sin(2 * np.pi * song[song_idx] * t)
        return Audio(data, rate=framerate, autoplay=True)
    play(silentnight) #supply what is missing to this function
    

    5. Decorating a Christmas Tree

    a) Import libraries.

    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
    import numpy as np
    

    b) Create an ornament class.

    class ORNAMENT:
        def __init__(self,x,y,image,size):   #properties
            self.x=x  #object's position is (x,y)
            self.y=y
            self.image=image  #name of the image file
            self.size=size  #specify the size
            
        def moveup(self,yamount):  #method to move the object vertically
            self.y = self.y+yamount
            
        def movedown(self,yamount):  #method to move the object vertically
            self.y = self.y-yamount
                        
                        
        def moveright(self,xamount):  #method to move the object horizontally
            self.x = self.x+xamount
            
        def moveleft(self,xamount):  #method to move the object horizontally
            self.x = self.x-xamount
            
        def zoom(self,factor):   #method to enlarge or shrink the object
            self.size= self.size*factor
    
            return  
    

    c) Create the ornament objects and position them on a tree.

    #create ornament objects
    o1=ORNAMENT(.1,.7,'O1.jpg',.3)
    o2=ORNAMENT(.1,.4,'O2.jpg',.2)
    o3=ORNAMENT(.1,.2,'O3.jpg',.3)
    star=ORNAMENT(.9,.5,'star.png',.1)
    
    #create a function to put the ornaments on a tree
    def decorate(o1,o2,o3,star):
        #make a graph
        fig, ax = plt.subplots(frameon=False)
        ax.set_aspect('equal')
    
        #add a tree
        treefig = mpimg.imread('xtree.png')
        imagebox = OffsetImage(treefig, zoom=0.5)
        ab = AnnotationBbox(imagebox, (0.5, 0.45),frameon=False)
        ax.add_artist(ab)
    
        orn1 = mpimg.imread(o1.image)
        imagebox= OffsetImage(orn1, zoom=o1.size)
        firstorn = AnnotationBbox(imagebox, (o1.x, o1.y),frameon=False)
        ax.add_artist(firstorn)
    
        orn2 = mpimg.imread(o2.image)
        imagebox= OffsetImage(orn2, zoom=o2.size)
        secondorn = AnnotationBbox(imagebox, (o2.x, o2.y),frameon=False)
        ax.add_artist(secondorn)
    
    
        orn3 = mpimg.imread(o3.image)
        imagebox= OffsetImage(orn3, zoom=o3.size)
        thirdorn = AnnotationBbox(imagebox, (o3.x, o3.y),frameon=False)
        ax.add_artist(thirdorn)
    
        starorn = mpimg.imread(star.image)
        imagebox= OffsetImage(starorn, zoom=star.size)
        thirdorn = AnnotationBbox(imagebox, (star.x, star.y),frameon=False)
        ax.add_artist(thirdorn)
        return
    

    Let’s start decorating!

    decorate(o1,o2,o3,star)
    
    ../../_images/73e0ca53d37915a865a5c91d16f7a4c97a94800fed442b5ce8ee1a7c064ed813.png

    Let’s move the first ornament (o1) to the right by .4 units.

    o1.moveright(.4)
    decorate(o1,o2,o3,star)
    
    ../../_images/53f1d2327d6617af0eb92c1e397183f310749bf170ddee57fd77476def27ed96.png

    ASSIGNMENT

    Now you can finish decorating the tree!

    Solution#

    o2.moveright(.3)
    o3.moveright(.5)
    decorate(o1,o2,o3,star)
    
    ../../_images/40e79ff6655d1e830301fae227025b2ea06c36378084c44f4134d43db5dbe719.png
    star.moveleft(.37)
    star.moveup(.5)
    decorate(o1,o2,o3,star)
    
    ../../_images/a3337cfb7e2eb9684af726f846ca66b973db406ba16f3bfefae1039b790f9edb.png